//
//  HomeListVC.swift
//  LeGou
//
//  Created by lxm on 2022/7/27.
//

import UIKit
import CoreData
import JXPagingView
import Kingfisher

class HomeJDListVC: ZMViewController, SubScrollDelegate, HomeHotFlowLayoutDelegate, ListRequestObjct {
    
    //MARK: --------------------属性--------------------
    var scrollViewDidScrollBlock: ((UIScrollView) -> ())?
    var listData = [JDGoodsModel]()
    var openHeaderRefresh = false
    var page = 1
    var pageSize = 10
    // 商品分类ID
    var cid = 0
    var refreshScrollView : UIScrollView {
        return collectionView
    }
    
    //MARK: --------------------UI控件--------------------
    var collectionView : UICollectionView!
    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        loadList()
    }
    //MARK: --------------------UI--------------------
    func setUI() {
        title = ""
        let layout = HomeHotFlowLayout()
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsets(top: 16, left: 12, bottom: 18, right: 12)
        layout.minimumLineSpacing = 7
        layout.minimumInteritemSpacing = 7
        layout.delegate = self
        collectionView = UICollectionView(frame: CGRect(), collectionViewLayout: layout)
        collectionView.register(UINib(nibName: "HomeGoodsCell", bundle: nil), forCellWithReuseIdentifier: "HomeGoodsCell")
        view.addSubview(collectionView)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        view.backgroundColor = "#F5F5F5".zm.hex()
        collectionView.alwaysBounceVertical = true
        collectionView.showsVerticalScrollIndicator = false
        addNodataScrollView(scrollView: collectionView)
        emptyTitle = "暂无数据"
        emptyImg = "nodata"
        addRefresh(scrollView: collectionView, addHead: openHeaderRefresh, addFoot: true) { [weak self] refresh in
            guard let self = self else {return}
            if refresh {
                self.page = 1
            }
            self.loadList()
        }
    }
    func addConstraints() {
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        
    }
    
    func giveSize(titleStr : String) -> CGSize {
        let imageStr = getAtrStr(titleStr: titleStr)
        let width = (SCREEN_W - 24 - 7 ) / 2 - 24
        imageStr.addAttributes([.font : UIFont.systemFont(ofSize: 14, weight: .medium)], range: NSRange(location: 0, length: imageStr.length))
        var size = imageStr.boundingRect(with: CGSize(width: width, height: 45), options: .usesLineFragmentOrigin, context: nil).size
        if size.height > 45 {
            size.height = 45
        }
        return size
    }
    
    func getAtrStr(titleStr : String) -> NSMutableAttributedString {
        let att = NSTextAttachment.init(data: nil, ofType: nil)
        att.image = UIImage.init(named: "home_jd")
        att.bounds = CGRect(x: 0, y: -4, width: 20, height: 20)
        let imageStr = NSMutableAttributedString(attachment: att)
        imageStr.append(NSMutableAttributedString.init(string: titleStr))
        return imageStr
    }
    
    func loadList(_ complete : (()->())? = nil) {
        let api = HomeAPI.home_jd(["limit" : pageSize, "page" : page])
        ZMUtil.listRequest(type: JDGoodsModel.self, api: api) { resp in
            self.listRequest(resp)
            if let complete = complete {
                complete()
            }
        }
    }

    //MARK: --------------------delegate--------------------
    func scrollView() -> UIScrollView {
        return self.collectionView
    }
    
    func scrollViewDidScroll(_ scrollViewDidScorllBolck: @escaping ((UIScrollView) -> ())) {
        scrollViewDidScrollBlock = scrollViewDidScorllBolck
    }
    // 处理手势被吃
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        checkBottomSpace()
    }
    // 处理手势被吃
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        checkBottomSpace()
    }
    // 处理手势被吃
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        checkBottomSpace()
    }
    // 处理手势被吃
    func checkBottomSpace() {
        let y = collectionView.contentOffset.y
        if y == collectionView.contentSize.height - collectionView.zm.height {
            collectionView.contentOffset = CGPoint(x: collectionView.contentOffset.x, y: collectionView.contentOffset.y - 1)
        }
    }
    // 处理手势被吃
    func minContentHeight() -> CGFloat {
        return view.zm.height + 1
    }
}

extension HomeJDListVC : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return listData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let data = listData[indexPath.row]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeGoodsCell", for: indexPath) as! HomeGoodsCell
        cell.label.attributedText = getAtrStr(titleStr: data.skuName)
        if let url = data.imageInfo?.imageList.first?.url {
            cell.img.zm.setImage(urlStr: url)
        }
        if let info = data.couponInfo?.couponList.first { 
            cell.coupon.text = info.discount.zm.toString(keep: 2) + "元"
        }
        cell.refund.text = "\(data.couponCommissionShare)元"
        
        cell.price.attributedText = "".zm.append(str: "¥", attri: ["f" : "12b", "c" : "#DC1826"])
            .zm.append(str: "\(data.lowestCouponPrice.zm.toString(keep: 2))", attri: ["f" : "18b", "c" : "#DC1826"])
            .zm.append(str: "券后", attri: ["f" : "12m", "c" : "#DC1826"])
        
        cell.subPrice.zm.setStrikethroughTitle(title: "¥\(data.lowestPrice.zm.toString(keep: 2))")
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width : CGFloat = (SCREEN_W - 24 - 7) / 2
        let d = listData[indexPath.row]
        let size = giveSize(titleStr: d.skuName)
        return CGSize(width: width, height: width + 15 + size.height + HomeGoodsCell.bootomH)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vc = JDDetailVC()
        vc.id = listData[indexPath.row].skuId
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
        KingfisherManager.shared.cache.clearMemoryCache()
    }
}

extension HomeJDListVC : JXPagingViewListViewDelegate {
    func listScrollView() -> UIScrollView { collectionView }
    
    func listView() -> UIView {
        return view
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if let scrollViewDidScrollBlock = scrollViewDidScrollBlock {
            scrollViewDidScrollBlock(scrollView)
        }
        listViewDidScrollCallback?(scrollView)
    }
}


